<?php
/**
 * 基础service
 * Created by PhpStorm.
 * User: 刘抱
 * Date: 2018/11/6
 * Time: 14:38
 */

namespace Home\Services;

use Think\Model;

class BaseService
{
    //获取多列数据
    protected static function getResult($table, $field, $where)
    {
        $db = M($table);
        $result = $db->field($field)->where($where)->select();
        return $result;
    }

    //获取单列数据
    protected static function getResultByField($table, $field, $where)
    {
        $db = M($table);
        $result = $db->field($field)->where($where)->find();
        return $result;
    }

    //获取多列数据加排序
    protected static function getResultOrder($table, $field, $where,$order)
    {
        $db = M($table);
        $result = $db->field($field)->where($where)->order($order)->select();
        return $result;
    }

    //添加数据
    protected static function insertData($table, $data)
    {
        $db = M($table);
        try {
            $result = $db->add($data);
            return $result;
        } catch (\Exception $e) {
            return false;
        }
    }

    //更新数据
    protected static function save($table, $data, $where)
    {
        $db = M($table);
        $result = $db->where($where)->save($data);
        return $result;
    }

    //删除数据
    protected static function del($table,$where)
    {
        $db = M($table);
        $result = $db->where($where)->delete();
        return $result;
    }

    public static function array_new($array, $field)
    {
        //取出指定相同列作为新key，其他列作为新key的value
        $new = array();
        foreach ($array as $val) {
            $type = $val[$field];
            !isset($new[$type]) && $new[$type] = array();
            $new[$type][] = $val;
        }
        return $new;
    }
}